/*
 * Licensed to the Tai Ping Jin Ke
 *
 * Copyright (c) 2022 .
 * All rights reserved.
 * 项目名称：呼叫中心-请求处理层-权限控制管理
 * 版权说明：本软件属太平金融科技服务(上海)有限公司所有，在未获得太平金融科技服务(上海)有限公司正式授权情况下，任何企业和个人，不能获取、阅读、安装、传播本软件涉及的任何受知识产权保护的内容。
 */
package com.taiping.cc.authorize.webapi.handler;

import com.taiping.cc.authorize.pojo.dto.AuthLoginDTO;
import com.taiping.cc.authorize.service.AccountService;
import com.taiping.cc.authorize.webapi.converter.AuthLoginBOConverter;
import com.taiping.dlt.pojo.bo.AuthLoginBO;
import com.taiping.dlt.pojo.query.AuthLoginQO;
import com.taipingframework.boot.web.response.result.ApiResult;
import com.taipingframework.boot.web.response.status.ApiStatusEnum;
import com.taipingframework.utility.exception.ApplicationException;
import com.taipingframework.utility.exception.SystemInterrupterException;
import com.taipingframework.utility.thread.wrapper.BenchmarksFuture;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * 账户管理web-api请求转发
 */
@Component
@RequiredArgsConstructor
public class AccountHandler {

    private final AccountService accountService;

    /**
     * 禁用账户/(逻辑)删除账户
     */
    public BenchmarksFuture<ApiResult<Boolean>> disableAccount(AuthLoginQO loginQO) {
        return BenchmarksFuture.supplyAsync(() -> {
            AuthLoginBO loginBO = AuthLoginBOConverter.convert(loginQO);
            return accountService.disableAccount(loginBO);
        }).exceptionally(throwable -> {
            throw new ApplicationException(throwable.getCause());
        });
    }

    /**
     * 获取登录认证数据
     */
    public BenchmarksFuture<ApiResult<Boolean>> collect(AuthLoginDTO authLoginDTO) {
        return BenchmarksFuture.supplyAsync(() ->
                accountService.receive(authLoginDTO)
        ).exceptionally(throwable -> {
            throw new ApplicationException(throwable.getCause());
        });
    }

    /**
     * 登录通-登录校验
     */
    public BenchmarksFuture<ApiResult<AuthLoginBO>> valid(AuthLoginQO loginQO) {
        return BenchmarksFuture.supplyAsync(() -> {
            if (StringUtils.isBlank(loginQO.getAccount())) {
                throw new SystemInterrupterException(ApiStatusEnum.ERR_A0110);
            }
            if (StringUtils.isBlank(loginQO.getPassword())) {
                throw new SystemInterrupterException(ApiStatusEnum.ERR_A0120);
            }

            AuthLoginBO authLoginBO = AuthLoginBOConverter.convert(loginQO);
            return accountService.valid(authLoginBO);
        }).exceptionally(throwable -> {
            throw new ApplicationException(throwable.getCause());
        });
    }

}
